package com.chenglai.commonutils.common;

import com.alibaba.cloud.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class Util {


    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4 & 0xF)];
        tempArr[1] = Digit[(mByte & 0xF)];
        String s = new String(tempArr);
        return s;
    }


    /**
     * StringUtils工具类方法
     * 获取一定长度的随机字符串，范围0-9
     *
     * @param length：指定字符串长度
     * @return 一定长度的随机字符串
     */
    public static String getRandomIntegerByLength(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * IpUtils工具类方法 获取真实的ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        try {
            String ip = request.getHeader("X-Forwarded-For");
            if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                int index = ip.indexOf(",");
                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            }
            ip = request.getHeader("X-Real-IP");
            if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
                return ip;
            }
            return request.getRemoteAddr();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 金额转换
     *
     * @param amount 具体金额
     * @return
     */
    public static String getMoney(String amount) {
        if (amount == null) {
            return "";
        }
        String currency = amount.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = Long.valueOf(0L);
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf(currency.substring(0, index + 3).replace(".",
                    ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf(currency.substring(0, index + 2).replace(".",
                    "") + 0);
        } else {
            amLong = Long.valueOf(currency.substring(0, index + 1).replace(".",
                    "")
                    + "00");
        }
        return amLong.toString();
    }



}
